// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class KnifeBag extends cc.Component {

    @property(cc.SpriteFrame)
    kniftIcon: cc.SpriteFrame = null;

    // 子弹发射音效
    @property(cc.AudioClip)
    throwAudioClip: cc.AudioClip = null;

    capacity: number = 10;  // 最大飞刀数
    count: number = 10;  // 飞刀袋里现有的飞刀

    // LIFE-CYCLE CALLBACKS:

    static inst: KnifeBag = null;


    onLoad () {

        KnifeBag.inst = this;

        // 飞刀的水平间距
        let space: number = this.node.width / this.capacity;

        // 创建10个飞刀
        let i: number = 0;

        // 动态创建节点
        for (i = 0; i < this.capacity; i++) {

            let knifeNode: cc.Node = new cc.Node();
            let knifeSprite: cc.Sprite = knifeNode.addComponent(cc.Sprite);

            knifeSprite.spriteFrame = this.kniftIcon;

            this.node.addChild(knifeNode);

            //scale缩放为0.4
            knifeNode.scale = 0.4;

            knifeNode.x = space * i + 20;
            knifeNode.y = 60;
        }
    }

    // 重置
    reset() {

        this.count = this.capacity;
        this.display();
    }

    // 消耗n个飞刀
    consume(n: number) {

        this.count -= n;

        if(this.count >= 0) {

            this.throwAudio();
        }

        // 暂时把0改为-1
        if(this.count < -1) {

            this.count = 0;
        }
        
        this.display();
    }

    // 飞刀出鞘, 投掷音效, 嗖的一声
    throwAudio() {

        if (this.throwAudioClip != null) {

            // 飞刀投掷时, 播放音效
            cc.audioEngine.play(this.throwAudioClip, false, 1);
        }
    }

    // 显示剩余的飞刀
    // active表示剩余飞刀
    display() {

        let node: cc.Node[] = this.node.children;

        let i: number = 0;

        for (i = 0; i < node.length; i++) {

            if(this.count > i) {

                node[i].active = true;
            }
            else {

                node[i].active = false;
            }
        }
    }

    start () {

    }

    // update (dt) {}
}
